package com.nowcoder.community.controller;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.entity.PageEntity;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.impl.MessageServiceImpl;
import com.nowcoder.community.service.impl.UserServiceImpl;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ChenJH
 * @since 2022-12-26
 */
@Controller
//@RequestMapping("/message")
public class MessageController implements CommunityConstant {
    @Autowired
    MessageServiceImpl messageService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    HostHolder hostHolder;

    @RequestMapping(path = "/letter/list", method = RequestMethod.GET)
    public String getLetterList(Model model, PageEntity pageEntity) {
        User user = hostHolder.getUser();
        pageEntity.setSize(5);

//        会话列表
        Page<Message> page = messageService.selectConversations(user.getId(), pageEntity);
        List<Message> conversationList = page.getRecords();
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message message : conversationList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("conversation", message);
                map.put("unreadCount", messageService.selectLetterUnreadCount(user.getId(), message.getConversationId()));
                map.put("letterCount", messageService.selectLetterCount(message.getConversationId()));
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target", userService.getById(targetId));

                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);
//        查询所有维度消息数量
        int letterUnreadCount = messageService.selectLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        System.out.println(letterUnreadCount);

        //        需要封装的内容
        model.addAttribute("page", page);
        long from = page.getCurrent() - 2;
        from = from < 1 ? 1 : from;
        long to = page.getCurrent() + 2;
        to = Math.min(to, page.getPages());
        model.addAttribute("from", from);
        model.addAttribute("to", to);
        model.addAttribute("path", "/letter/list");

        return "/site/letter";
    }

    @RequestMapping(path = "/letter/detail/{conversationId}", method = RequestMethod.GET)
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, PageEntity pageEntity, Model model) {
        pageEntity.setSize(5);

//        私信列表
        Page<Message> page = messageService.selectLetters(conversationId, pageEntity);
        List<Message> letterList = page.getRecords();
        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.getById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);

//        私信目标
        model.addAttribute("target", getLetterTarget(conversationId));

//        设置已读
        List<Integer> ids = getLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.updateStatus(ids, 1);
        }

        //        需要封装的内容
        model.addAttribute("page", page);
        long from = page.getCurrent() - 2;
        from = from < 1 ? 1 : from;
        long to = page.getCurrent() + 2;
        to = Math.min(to, page.getPages());
        model.addAttribute("from", from);
        model.addAttribute("to", to);
        model.addAttribute("path", "/letter/detail/" + conversationId);
        return "/site/letter-detail";
    }

    /**
     * 返回 处于未读状态的信息
     *
     * @param letterList
     * @return
     */
    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                int userid = hostHolder.getUser().getId();
                if (Objects.equals(hostHolder.getUser().getId(), message.getToId()) && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }

    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (hostHolder.getUser().getId() == id0) {
            return userService.getById(id1);
        } else {
            return userService.getById(id0);
        }
    }

    @RequestMapping(path = "/letter/send", method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName, String content) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, toName);
        User target = userService.getOne(wrapper);

        if (target == null) {
            return CommunityUtil.getJsonString(1, "目标用户不存在");
        }

        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }

        message.setContent(content);
        message.setCreateTime(LocalDateTime.now());
        message.setStatus(0);
        messageService.addMessage(message);

        return CommunityUtil.getJsonString(0);
    }


    @RequestMapping(path = "/notice/list", method = RequestMethod.GET)
    public String getNoticeList(Model model) {
        User user = hostHolder.getUser();
//        查询评论通知
        Message message = messageService.findLatestNotice(user.getId(), TOPIC_COMMENT);
        if (message != null) {
            HashMap<String, Object> messageVO = new HashMap<>();

            messageVO.put("message", message);
//            因为转为json后 存放到数据库中 被转义了
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.getById((Serializable) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
            messageVO.put("unread", unread);
            model.addAttribute("commentNotice", messageVO);

        }
//        查询点赞通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);

        if (message != null) {
            HashMap<String, Object> messageVO = new HashMap<>();

            messageVO.put("message", message);
//            因为转为json后 存放到数据库中 被转义了
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.getById((Serializable) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVO.put("unread", unread);
            model.addAttribute("likeNotice", messageVO);

        }
//        查询关注通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);

        if (message != null) {
            HashMap<String, Object> messageVO = new HashMap<>();

            messageVO.put("message", message);
//            因为转为json后 存放到数据库中 被转义了
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userService.getById((Serializable) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
//            因为关注后是连接到那个人的个人主页  不需要帖子连接了
//            messageVO.put("postId",data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("count", count);

            int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVO.put("unread", unread);
            model.addAttribute("followNotice", messageVO);

        }

//      查询未读数量
        int letterUnreadCount = messageService.selectLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);


        return "/site/notice";
    }

    @RequestMapping(path = "/notice/detail/{topic}", method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("topic") String topic, PageEntity pageEntity, Model model) {
        User user = hostHolder.getUser();
        pageEntity.setSize(5);

        Page<Message> page = messageService.findNotices(user.getId(), topic, pageEntity);
        List<Message> noticeList = page.getRecords();
        ArrayList<Map<String, Object>> noticeVoList = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
                HashMap<String, Object> map = new HashMap<>();
//                通知
                map.put("notice", notice);
//                内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                HashMap<String, Object> data = JSONObject.parseObject(content, HashMap.class);

                map.put("user", userService.getById((Serializable) data.get("userId")));

                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
//                通知作者
                map.put("fromUser", userService.getById(notice.getFromId()));
                noticeVoList.add(map);
            }
        }
        model.addAttribute("notices",noticeVoList);

//        设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }



        //        需要封装的内容
        model.addAttribute("page", page);
        long from = page.getCurrent() - 2;
        from = from < 1 ? 1 : from;
        long to = page.getCurrent() + 2;
        to = Math.min(to, page.getPages());
        model.addAttribute("from", from);
        model.addAttribute("to", to);
        model.addAttribute("path", "/notice/detail/" + topic);
        return "/site/notice-detail";
    }


}
